package mju.cn.twoweek.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * @program: java-ee_31
 * @description:
 * @author: HP
 * @time: 2020/9/21 11:41
 */
public class SqlSessionFactoryUtils {
    private static SqlSessionFactory sqlSessionFactory = null;
    private SqlSessionFactoryUtils(){}
    public static SqlSessionFactory getSqlSessionFactory(){
        if (sqlSessionFactory != null){
            return sqlSessionFactory;
        }
        String configName ="mybatisConfig.xml";
        InputStream inputStream;
        try {
            inputStream = Resources.getResourceAsStream(configName);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return sqlSessionFactory;
    }
    public static SqlSession openSqlSession(){
        if(sqlSessionFactory == null){
            getSqlSessionFactory();
        }
        return sqlSessionFactory.openSession();
    }
}
